home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Internet Tools 1993 July / Internet Tools.iso / RockRidge / mail / pine / imap-3.0 / ANSI / c-client / os_bsi.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-05-18  |  16.8 KB  |  599 lines

  1. /*
  2.  * Program:    Operating-system dependent routines -- BSDI BSD/386 version
  3.  *
  4.  * Author:       Mike Santangelo (based on NeXT port by Mark Crispin)
  5.  *               UMCEES/CBL Computer and Network Systems Department
  6.  *               Solomons, Maryland
  7.  *               Internet: mike@cbl.umd.edu
  8.  *
  9.  * Date:         5 March 1993
  10.  * Last Edited:  19 March 1993
  11.  *
  12.  * Copyright 1993 by the University of Washington.
  13.  *
  14.  *  Permission to use, copy, modify, and distribute this software and its
  15.  * documentation for any purpose and without fee is hereby granted, provided
  16.  * that the above copyright notice appears in all copies and that both the
  17.  * above copyright notice and this permission notice appear in supporting
  18.  * documentation, and that the name of the University of Washington not be
  19.  * used in advertising or publicity pertaining to distribution of the software
  20.  * without specific, written prior permission.  This software is made available
  21.  * "as is", and
  22.  * THE UNIVERSITY OF WASHINGTON DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED,
  23.  * WITH REGARD TO THIS SOFTWARE, INCLUDING WITHOUT LIMITATION ALL IMPLIED
  24.  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND IN
  25.  * NO EVENT SHALL THE UNIVERSITY OF WASHINGTON BE LIABLE FOR ANY SPECIAL,
  26.  * INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  27.  * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, TORT
  28.  * (INCLUDING NEGLIGENCE) OR STRICT LIABILITY, ARISING OUT OF OR IN CONNECTION
  29.  * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  30.  *
  31.  */
  32.  
  33. /* TCP input buffer */
  34.  
  35. #define BUFLEN 8192
  36.  
  37.  
  38. /* TCP I/O stream (must be before osdep.h is included) */
  39.  
  40. #define TCPSTREAM struct tcp_stream
  41. TCPSTREAM {
  42.   char *host;            /* host name */
  43.   char *localhost;        /* local host name */
  44.   int tcpsi;            /* input socket */
  45.   int tcpso;            /* output socket */
  46.   int ictr;            /* input counter */
  47.   char *iptr;            /* input pointer */
  48.   char ibuf[BUFLEN];        /* input buffer */
  49. };
  50.  
  51.  
  52. #include "mail.h"
  53. #include "osdep.h"
  54. #include <sys/time.h>
  55. #include <sys/socket.h>
  56. #include <netinet/in.h>
  57. #include <netdb.h>
  58. #include <ctype.h>
  59. #include <errno.h>
  60. extern int errno;        /* just in case */
  61. #include <pwd.h>
  62. #include <syslog.h>
  63. #include "misc.h"
  64. extern char *crypt();
  65.  
  66. /* Write current time in RFC 822 format
  67.  * Accepts: destination string
  68.  */
  69.  
  70. char *days[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
  71.  
  72. void rfc822_date (char *date)
  73. {
  74.   int zone;
  75.   char *zonename;
  76.   struct tm *t;
  77.   struct timeval tv;
  78.   struct timezone tz;
  79.   gettimeofday (&tv,&tz);    /* get time and timezone poop */
  80.   t = localtime (&tv.tv_sec);    /* convert to individual items */
  81.   zone = t->tm_gmtoff/60;    /* get timezone from TZ environment stuff */
  82.   zonename = t->tm_zone;
  83.                 /* and output it */
  84.   sprintf (date,"%s, %d %s %d %02d:%02d:%02d %+03d%02d (%s)",
  85.        days[t->tm_wday],t->tm_mday,months[t->tm_mon],t->tm_year+1900,
  86.        t->tm_hour,t->tm_min,t->tm_sec,zone/60,abs (zone) % 60,zonename);
  87. }
  88.  
  89. /* Get a block of free storage
  90.  * Accepts: size of desired block
  91.  * Returns: free storage block
  92.  */
  93.  
  94. void *fs_get (size_t size)
  95. {
  96.   void *block = malloc (size);
  97.   if (!block) fatal ("Out of free storage");
  98.   return (block);
  99. }
  100.  
  101.  
  102. /* Resize a block of free storage
  103.  * Accepts: ** pointer to current block
  104.  *        new size
  105.  */
  106.  
  107. void fs_resize (void **block,size_t size)
  108. {
  109.   if (!(*block = realloc (*block,size))) fatal ("Can't resize free storage");
  110. }
  111.  
  112.  
  113. /* Return a block of free storage
  114.  * Accepts: ** pointer to free storage block
  115.  */
  116.  
  117. void fs_give (void **block)
  118. {
  119.   free (*block);
  120.   *block = NIL;
  121. }
  122.  
  123.  
  124. /* Report a fatal error
  125.  * Accepts: string to output
  126.  */
  127.  
  128. void fatal (char *string)
  129. {
  130.   mm_fatal (string);        /* pass up the string */
  131.   syslog (LOG_ALERT,"IMAP C-Client crash: %s",string);
  132.   abort ();            /* die horribly */
  133. }
  134.  
  135. /* Copy string with CRLF newlines
  136.  * Accepts: destination string
  137.  *        pointer to size of destination string
  138.  *        source string
  139.  *        length of source string
  140.  */
  141.  
  142. char *strcrlfcpy (char **dst,unsigned long *dstl,char *src,unsigned long srcl)
  143. {
  144.   long i,j;
  145.   char *d = src;
  146.                 /* count number of LF's in source string(s) */
  147.   for (i = srcl,j = 0; j < srcl; j++) if (*d++ == '\012') i++;
  148.   if (i > *dstl) {        /* resize if not enough space */
  149.     fs_give ((void **) dst);    /* fs_resize does an unnecessary copy */
  150.     *dst = (char *) fs_get ((*dstl = i) + 1);
  151.   }
  152.   d = *dst;            /* destination string */
  153.                 /* copy strings, inserting CR's before LF's */
  154.   while (srcl--) switch (*src) {
  155.   case '\015':            /* unlikely carriage return */
  156.     *d++ = *src++;        /* copy it and any succeeding linefeed */
  157.     if (srcl && *src == '\012') {
  158.       *d++ = *src++;
  159.       srcl--;
  160.     }
  161.     break;
  162.   case '\012':            /* line feed? */
  163.     *d++ ='\015';        /* yes, prepend a CR, drop into default case */
  164.   default:            /* ordinary chararacter */
  165.     *d++ = *src++;        /* just copy character */
  166.     break;
  167.   }
  168.   *d = '\0';            /* tie off destination */
  169.   return *dst;            /* return destination */
  170. }
  171.  
  172.  
  173. /* Length of string after strcrlfcpy applied
  174.  * Accepts: source string
  175.  *        length of source string
  176.  */
  177.  
  178. unsigned long strcrlflen (STRING *s)
  179. {
  180.   unsigned long pos = GETPOS (s);
  181.   unsigned long i = SIZE (s);
  182.   unsigned long j = i;
  183.   while (j--) switch (SNX (s)) {/* search for newlines */
  184.   case '\015':            /* unlikely carriage return */
  185.     if (j && (CHR (s) == '\012')) {
  186.       SNX (s);            /* eat the line feed */
  187.       j--;
  188.     }
  189.     break;
  190.   case '\012':            /* line feed? */
  191.     i++;
  192.   default:            /* ordinary chararacter */
  193.     break;
  194.   }
  195.   SETPOS (s,pos);        /* restore old position */
  196.   return i;
  197. }
  198.  
  199. /* Server log in
  200.  * Accepts: user name string
  201.  *        password string
  202.  *        optional place to return home directory
  203.  * Returns: T if password validated, NIL otherwise
  204.  */
  205.  
  206. long server_login (char *user,char *pass,char **home,int argc,char *argv[])
  207. {
  208.   struct passwd *pw = getpwnam (lcase (user));
  209.                 /* no entry for this user or root */
  210.   if (!(pw && pw->pw_uid)) return NIL;
  211.                 /* validate password */
  212.   if (strcmp (pw->pw_passwd,(char *) crypt (pass,pw->pw_passwd))) return NIL;
  213.   setgid (pw->pw_gid);        /* all OK, login in as that user */
  214.   initgroups (user,pw->pw_gid);    /* initialize groups */
  215.   setuid (pw->pw_uid);
  216.                 /* note home directory */
  217.   if (home) *home = cpystr (pw->pw_dir);
  218.   return T;
  219. }
  220.  
  221. /* Return my user name
  222.  * Returns: my user name
  223.  */
  224.  
  225. char *uname = NIL;
  226.  
  227. char *myusername ()
  228. {
  229.   return uname ? uname : (uname = cpystr (getpwuid (geteuid ())->pw_name));
  230. }
  231.  
  232.  
  233. /* Return my home directory name
  234.  * Returns: my home directory name
  235.  */
  236.  
  237. char *hdname = NIL;
  238.  
  239. char *myhomedir ()
  240. {
  241.   return hdname ? hdname : (hdname = cpystr (getpwuid (geteuid ())->pw_dir));
  242. }
  243.  
  244.  
  245. /* Build status lock file name
  246.  * Accepts: scratch buffer
  247.  *        file name
  248.  * Returns: name of file to lock
  249.  */
  250.  
  251. char *lockname (char *tmp,char *fname)
  252. {
  253.   int i;
  254.   sprintf (tmp,"/tmp/.%s",fname);
  255.   for (i = 6; i < strlen (tmp); ++i) if (tmp[i] == '/') tmp[i] = '\\';
  256.   return tmp;            /* note name for later */
  257. }
  258.   
  259. /* TCP/IP open
  260.  * Accepts: host name
  261.  *        contact port number
  262.  * Returns: TCP/IP stream if success else NIL
  263.  */
  264.  
  265. TCPSTREAM *tcp_open (char *host,int port)
  266. {
  267.   TCPSTREAM *stream = NIL;
  268.   int sock;
  269.   char *s;
  270.   struct sockaddr_in sin;
  271.   struct hostent *host_name;
  272.   char hostname[MAILTMPLEN];
  273.   char tmp[MAILTMPLEN];
  274.   /* The domain literal form is used (rather than simply the dotted decimal
  275.      as with other Unix programs) because it has to be a valid "host name"
  276.      in mailsystem terminology. */
  277.                 /* look like domain literal? */
  278.   if (host[0] == '[' && host[(strlen (host))-1] == ']') {
  279.     strcpy (hostname,host+1);    /* yes, copy number part */
  280.     hostname[(strlen (hostname))-1] = '\0';
  281.     if ((sin.sin_addr.s_addr = inet_addr (hostname)) != -1) {
  282.       sin.sin_family = AF_INET;    /* family is always Internet */
  283.       strcpy (hostname,host);    /* hostname is user's argument */
  284.     }
  285.     else {
  286.       sprintf (tmp,"Bad format domain-literal: %.80s",host);
  287.       mm_log (tmp,ERROR);
  288.       return NIL;
  289.     }
  290.   }
  291.  
  292.   else {            /* lookup host name, note that brain-dead Unix
  293.                    requires lowercase! */
  294.     strcpy (hostname,host);    /* in case host is in write-protected memory */
  295.     if ((host_name = gethostbyname (lcase (hostname)))) {
  296.                 /* copy address type */
  297.       sin.sin_family = host_name->h_addrtype;
  298.                 /* copy host name */
  299.       strcpy (hostname,host_name->h_name);
  300.                 /* copy host addresses */
  301.       memcpy (&sin.sin_addr,host_name->h_addr,host_name->h_length);
  302.     }
  303.     else {
  304.       switch (h_errno) {
  305.     case HOST_NOT_FOUND:    /* authoritative error */
  306.       s = "No such host as %.80s";
  307.       break;
  308.     case TRY_AGAIN:        /* non-authoritative error */
  309.       s = "Transient error for host %.80s, try again";
  310.       break;
  311.     case NO_RECOVERY:    /* non-recoverable errors */
  312.       s = "Non-recoverable error looking up host %.80s";
  313.       break;
  314.     case NO_DATA:        /* no data record of requested type */
  315.       s = "No IP address known for host %.80s";
  316.       break;
  317.     default:
  318.       s = "Unknown error for host %.80s";
  319.       break;
  320.       }
  321.       sprintf (tmp,s,host);
  322.       mm_log (tmp,ERROR);
  323.       return NIL;
  324.     }
  325.   }
  326.  
  327.                 /* copy port number in network format */
  328.   if (!(sin.sin_port = htons (port))) fatal ("Bad port argument to tcp_open");
  329.                 /* get a TCP stream */
  330.   if ((sock = socket (sin.sin_family,SOCK_STREAM,0)) < 0) {
  331.     sprintf (tmp,"Unable to create TCP socket: %s",strerror (errno));
  332.     mm_log (tmp,ERROR);
  333.     return NIL;
  334.   }
  335.                 /* open connection */
  336.   if (connect (sock,(struct sockaddr *)&sin,sizeof (sin)) < 0) {
  337.     sprintf (tmp,"Can't connect to %.80s,%d: %s",hostname,port,
  338.          strerror (errno));
  339.     mm_log (tmp,ERROR);
  340.     return NIL;
  341.   }
  342.                 /* create TCP/IP stream */
  343.   stream = (TCPSTREAM *) fs_get (sizeof (TCPSTREAM));
  344.                 /* copy official host name */
  345.   stream->host = cpystr (hostname);
  346.                 /* get local name */
  347.   gethostname (tmp,MAILTMPLEN-1);
  348.   stream->localhost = cpystr ((host_name = gethostbyname (tmp)) ?
  349.                   host_name->h_name : tmp);
  350.                 /* init sockets */
  351.   stream->tcpsi = stream->tcpso = sock;
  352.   stream->ictr = 0;        /* init input counter */
  353.   return stream;        /* return success */
  354. }
  355.   
  356. /* TCP/IP authenticated open
  357.  * Accepts: host name
  358.  *        service name
  359.  * Returns: TCP/IP stream if success else NIL
  360.  */
  361.  
  362. TCPSTREAM *tcp_aopen (char *host,char *service)
  363. {
  364.   TCPSTREAM *stream = NIL;
  365.   struct hostent *host_name;
  366.   char hostname[MAILTMPLEN];
  367.   int i;
  368.   int pipei[2],pipeo[2];
  369.   /* The domain literal form is used (rather than simply the dotted decimal
  370.      as with other Unix programs) because it has to be a valid "host name"
  371.      in mailsystem terminology. */
  372.                 /* look like domain literal? */
  373.   if (host[0] == '[' && host[i = (strlen (host))-1] == ']') {
  374.     strcpy (hostname,host+1);    /* yes, copy without brackets */
  375.     hostname[i-1] = '\0';
  376.   }
  377.                 /* note that Unix requires lowercase! */
  378.   else if (host_name = gethostbyname (lcase (strcpy (hostname,host))))
  379.     strcpy (hostname,host_name->h_name);
  380.                 /* make command pipes */
  381.   if (pipe (pipei) < 0) return NIL;
  382.   if (pipe (pipeo) < 0) {
  383.     close (pipei[0]); close (pipei[1]);
  384.     return NIL;
  385.   }
  386.   if ((i = fork ()) < 0) {    /* make inferior process */
  387.     close (pipei[0]); close (pipei[1]);
  388.     close (pipeo[0]); close (pipeo[1]);
  389.     return NIL;
  390.   }
  391.   if (i) {            /* parent? */
  392.     close (pipei[1]);        /* close child's side of the pipes */
  393.     close (pipeo[0]);
  394.   }
  395.   else {            /* child */
  396.     dup2 (pipei[1],1);        /* parent's input is my output */
  397.     dup2 (pipei[1],2);        /* parent's input is my error output too */
  398.     close (pipei[0]); close (pipei[1]);
  399.     dup2 (pipeo[0],0);        /* parent's output is my input */
  400.     close (pipeo[0]); close (pipeo[1]);
  401.                 /* now run it */
  402.     execl ("/usr/bin/rsh","rsh",hostname,"exec",service,0);
  403.     _exit (1);            /* spazzed */
  404.   }
  405.  
  406.                 /* create TCP/IP stream */
  407.   stream = (TCPSTREAM *) fs_get (sizeof (TCPSTREAM));
  408.                 /* copy official host name */
  409.   stream->host = cpystr (hostname);
  410.                 /* get local name */
  411.   gethostname (hostname,MAILTMPLEN-1);
  412.   stream->localhost = cpystr ((host_name = gethostbyname (hostname)) ?
  413.                   host_name->h_name : hostname);
  414.   stream->tcpsi = pipei[0];    /* init sockets */
  415.   stream->tcpso = pipeo[1];
  416.   stream->ictr = 0;        /* init input counter */
  417.   return stream;        /* return success */
  418. }
  419.  
  420. /* TCP/IP receive line
  421.  * Accepts: TCP/IP stream
  422.  * Returns: text line string or NIL if failure
  423.  */
  424.  
  425. char *tcp_getline (TCPSTREAM *stream)
  426. {
  427.   int n,m;
  428.   char *st,*ret,*stp;
  429.   char c = '\0';
  430.   char d;
  431.                 /* make sure have data */
  432.   if (!tcp_getdata (stream)) return NIL;
  433.   st = stream->iptr;        /* save start of string */
  434.   n = 0;            /* init string count */
  435.   while (stream->ictr--) {    /* look for end of line */
  436.     d = *stream->iptr++;    /* slurp another character */
  437.     if ((c == '\015') && (d == '\012')) {
  438.       ret = (char *) fs_get (n--);
  439.       memcpy (ret,st,n);    /* copy into a free storage string */
  440.       ret[n] = '\0';        /* tie off string with null */
  441.       return ret;
  442.     }
  443.     n++;            /* count another character searched */
  444.     c = d;            /* remember previous character */
  445.   }
  446.                 /* copy partial string from buffer */
  447.   memcpy ((ret = stp = (char *) fs_get (n)),st,n);
  448.                 /* get more data from the net */
  449.   if (!tcp_getdata (stream)) return NIL;
  450.                 /* special case of newline broken by buffer */
  451.   if ((c == '\015') && (*stream->iptr == '\012')) {
  452.     stream->iptr++;        /* eat the line feed */
  453.     stream->ictr--;
  454.     ret[n - 1] = '\0';        /* tie off string with null */
  455.   }
  456.                 /* else recurse to get remainder */
  457.   else if (st = tcp_getline (stream)) {
  458.     ret = (char *) fs_get (n + 1 + (m = strlen (st)));
  459.     memcpy (ret,stp,n);        /* copy first part */
  460.     memcpy (ret + n,st,m);    /* and second part */
  461.     fs_give ((void **) &stp);    /* flush first part */
  462.     fs_give ((void **) &st);    /* flush second part */
  463.     ret[n + m] = '\0';        /* tie off string with null */
  464.   }
  465.   return ret;
  466. }
  467.  
  468. /* TCP/IP receive buffer
  469.  * Accepts: TCP/IP stream
  470.  *        size in bytes
  471.  *        buffer to read into
  472.  * Returns: T if success, NIL otherwise
  473.  */
  474.  
  475. long tcp_getbuffer (TCPSTREAM *stream,unsigned long size,char *buffer)
  476. {
  477.   unsigned long n;
  478.   char *bufptr = buffer;
  479.   while (size > 0) {        /* until request satisfied */
  480.     if (!tcp_getdata (stream)) return NIL;
  481.     n = min (size,stream->ictr);/* number of bytes to transfer */
  482.                 /* do the copy */
  483.     memcpy (bufptr,stream->iptr,n);
  484.     bufptr += n;        /* update pointer */
  485.     stream->iptr +=n;
  486.     size -= n;            /* update # of bytes to do */
  487.     stream->ictr -=n;
  488.   }
  489.   bufptr[0] = '\0';        /* tie off string */
  490.   return T;
  491. }
  492.  
  493.  
  494. /* TCP/IP receive data
  495.  * Accepts: TCP/IP stream
  496.  * Returns: T if success, NIL otherwise
  497.  */
  498.  
  499. long tcp_getdata (TCPSTREAM *stream)
  500. {
  501.   fd_set fds;
  502.   FD_ZERO (&fds);        /* initialize selection vector */
  503.   if (stream->tcpsi < 0) return NIL;
  504.   while (stream->ictr < 1) {    /* if nothing in the buffer */
  505.     FD_SET (stream->tcpsi,&fds);/* set bit in selection vector */
  506.                 /* block and read */
  507.     if ((select (stream->tcpsi+1,&fds,0,0,0) < 0) ||
  508.     ((stream->ictr = read (stream->tcpsi,stream->ibuf,BUFLEN)) < 1)) {
  509.       close (stream->tcpsi);    /* nuke the socket */
  510.       if (stream->tcpsi != stream->tcpso) close (stream->tcpso);
  511.       stream->tcpsi = stream->tcpso = -1;
  512.       return NIL;
  513.     }
  514.     stream->iptr = stream->ibuf;/* point at TCP buffer */
  515.   }
  516.   return T;
  517. }
  518.  
  519. /* TCP/IP send string as record
  520.  * Accepts: TCP/IP stream
  521.  *        string pointer
  522.  * Returns: T if success else NIL
  523.  */
  524.  
  525. long tcp_soutr (TCPSTREAM *stream,char *string)
  526. {
  527.   return tcp_sout (stream,string,(unsigned long) strlen (string));
  528. }
  529.  
  530.  
  531. /* TCP/IP send string
  532.  * Accepts: TCP/IP stream
  533.  *        string pointer
  534.  *        byte count
  535.  * Returns: T if success else NIL
  536.  */
  537.  
  538. long tcp_sout (TCPSTREAM *stream,char *string,unsigned long size)
  539. {
  540.   int i;
  541.   fd_set fds;
  542.   FD_ZERO (&fds);        /* initialize selection vector */
  543.   if (stream->tcpso < 0) return NIL;
  544.   while (size > 0) {        /* until request satisfied */
  545.     FD_SET (stream->tcpso,&fds);/* set bit in selection vector */
  546.     if ((select (stream->tcpso+1,0,&fds,0,0) < 0) ||
  547.     ((i = write (stream->tcpso,string,size)) < 0)) {
  548.       puts (strerror (errno));
  549.       close (stream->tcpsi);    /* nuke the socket */
  550.       if (stream->tcpsi != stream->tcpso) close (stream->tcpso);
  551.       stream->tcpsi = stream->tcpso = -1;
  552.       return NIL;
  553.     }
  554.     size -= i;            /* count this size */
  555.     string += i;
  556.   }
  557.   return T;            /* all done */
  558. }
  559.  
  560. /* TCP/IP close
  561.  * Accepts: TCP/IP stream
  562.  */
  563.  
  564. void tcp_close (TCPSTREAM *stream)
  565. {
  566.  
  567.   if (stream->tcpsi >= 0) {    /* no-op if no socket */
  568.     close (stream->tcpsi);    /* nuke the socket */
  569.     if (stream->tcpsi != stream->tcpso) close (stream->tcpso);
  570.     stream->tcpsi = stream->tcpso = -1;
  571.   }
  572.                 /* flush host names */
  573.   fs_give ((void **) &stream->host);
  574.   fs_give ((void **) &stream->localhost);
  575.   fs_give ((void **) &stream);    /* flush the stream */
  576. }
  577.  
  578.  
  579. /* TCP/IP get host name
  580.  * Accepts: TCP/IP stream
  581.  * Returns: host name for this stream
  582.  */
  583.  
  584. char *tcp_host (TCPSTREAM *stream)
  585. {
  586.   return stream->host;        /* return host name */
  587. }
  588.  
  589.  
  590. /* TCP/IP get local host name
  591.  * Accepts: TCP/IP stream
  592.  * Returns: local host name
  593.  */
  594.  
  595. char *tcp_localhost (TCPSTREAM *stream)
  596. {
  597.   return stream->localhost;    /* return local host name */
  598. }
  599.